package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.Result;
import com.example.entity.SCategory;
import com.example.service.SCategoryService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/categories")
public class SCategoryController {
    @Autowired
    private SCategoryService categoryService;


    @ApiOperation("根据功能种类新增")
    @PostMapping("/addByFunc")
    public Result<?> addCategoryByFunc(@RequestBody SCategory sCategory){
        categoryService.save(sCategory);
        return Result.success();
    }

    @ApiOperation("单选/多选删除种类")
    @DeleteMapping("/delete")
    public Result<?> deleteCategories(@RequestBody List<Long> list){
        categoryService.removeBatchByIds(list);
        return Result.success();
    }


    @ApiOperation("更新种类信息")
    @PostMapping("/update")
    public Result<?> updateCategory(@RequestBody SCategory sCategory){
        LambdaQueryWrapper<SCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SCategory::getId,sCategory.getId());
        categoryService.update(sCategory,wrapper);
        return Result.success();
    }

    @ApiOperation("查看种类，可根据名字模糊查询")
    @GetMapping("/get")
    public Result<List<SCategory>> selectBrand(@RequestParam(required = false, defaultValue = "") String name){
        LambdaQueryWrapper<SCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(SCategory::getName,name);
        List<SCategory> list = categoryService.list(wrapper);
        return  Result.success(list);
    }


    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(required = false, defaultValue = "") String name,
                              @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                              @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<SCategory> query = Wrappers.<SCategory>lambdaQuery().like(SCategory::getName, name).orderByDesc(SCategory::getId);
        IPage<SCategory> page = categoryService.page(new Page<>(pageNum, pageSize), query);
        return Result.success(page);
    }
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        categoryService.removeById(id);
        return Result.success();
    }
}
